//config
var C = {
	postUrl: '/pk/pk',
	dataUrl:'/pk/data',
	winUrl:'/pk/prizeChoosen',

	roundCount: 35,
	roundTime: 10, //单位秒
	preloadCount: 4, //预加载数量

	pageSize: {
		x : $(window).width(),
		y : $(window).height()
	}
};
var S = {
	curRound: 1,
	data: itemJson, //数据
	picTpl: template($('#img_tpl').html()),
	prizeTpl: template($('#prize_tpl').html()),
	config: C
};
var EVT = {
	picChosen : 'pic.chosen',
	prizeShow : 'prize.show',
	prizeSuccess: 'prize.success',
	gameover : 'game.over',
	roundStart : 'round.start',
	roundResult : 'round.result',
	roundSuccess : 'round.success',
	noMoney : 'error.nomoney'
}
var UI = {};


UI.drawRoundPics = function(data){
	var n = data.round;
	var group = S.data[n];
	var htmlStr = '';
	var center = C.pageSize.x / 2,
		spaceEdge = C.pageSize.x / 15,
		spaceBetween = spaceEdge,
		width = center - (spaceEdge + spaceBetween/2);

	for(var i=0; i < group.length; ++i){
		var pic = group[i];
		var tplData = {
			width: width - 20, //20为相框宽度
			left: (width + spaceBetween) *i + spaceEdge,
			pic_show_url: pic.pic_show_url,
			id: pic.id,
			group: n,
			colorIndex: n % 10 + 1
		}
		htmlStr += S.picTpl(tplData);
	}
	
	$('#pk_main').fadeOut(function(){
		$('#pk_main').html(htmlStr);
	}).fadeIn();
};
UI.initDataPk = function(){
	$('[data-pk]').live('click', function(){
		var group = $(this).attr('data-group'),
			winner = $(this).attr('data-pk'),
			loser;
		//现在仅抽出来一个loser,倒霉的.(仅适用于一组两个的场景)
		for (var i = 0; i < S.data[group].length; i++) {
			if(S.data[group][i].id != winner){
				loser = S.data[group][i].id;
			}
		};

		EC.fire(EVT.picChosen,{winner:winner, loser:loser});
		
		$.post(C.postUrl,{
			w: winner,
			l: loser,
			token: token
		}, function(data){
			EC.fire(EVT.roundResult, data);
			S.handleRoundResult(data);
		});
	});
};
UI.popup = function(el, closeFn){
	UI._popup = $(el).reveal({
		closeonbackgroundclick: false

	});
};
UI.closePopup = function(){
	UI._popup.trigger('reveal:close');
};
UI.confirm = function(content, ok , cancel){
	art.confirm(content, ok ,cancel);
};
UI.alert = function(content, ok ){
	art.alert(content, ok);
};


UI.showPrize = function(data){
	var htmlStr = S.prizeTpl({prizes:data.prize}),
		prizeEl = $(htmlStr);
	prizeEl.appendTo(document.body);
	UI.popup(prizeEl);
	prizeEl.find('[data-prize-id]').click(function(){
		UI.closePopup();
		S.winPrize($(this).attr('data-prize-id'));
	});
	prizeEl.find('.nextRound').click(function(){
		UI.closePopup();
		S.nextRound();
	});

	/*
	if(!confirm('恭喜你,赢得了: ' + data.prize[0].name + ',是否继续冲击更高奖?')){
		S.winPrize(data.prize[0].id);
	} else{
		S.nextRound();
	}
	*/
};
UI.gameover = function(data){
	UI.confirm('功亏一篑, 您已经连续选对了' + (S.curRound -1) +'次, 是否重新开始?', function(){
		window.location.reload();
	}, function(){
		//TODO
	});
	/*
	if(confirm('功亏一篑, 您已经连续选对了' + (S.curRound -1) +'次, 是否重新开始?') ){
		window.location.reload();
	} else {
		//TODO
	}
	*/
};
UI.prizeSuccess = function(data){
	UI.confirm('领奖成功, 再玩一局?', function(){
		window.location.reload();
	}, function(){
		//TODO
	});
	/*
	if( confirm('领奖成功, 再玩一局?') ) {
		window.location.reload();
	}
	*/
};
UI.noMoney = function(data){
	UI.alert("余额不足,请充值", function(){
		//TODO
	});
	//alert('No Flowers.');
}

UI.initialize = function (){

	(function(d){
		d.okValue = '确定';
		d.cancelValue = '取消';
		d.title = ' ';
	})(art.dialog.defaults);

	UI.initDataPk();
	EC.on(EVT.roundStart, UI.drawRoundPics);
	EC.on(EVT.prizeShow, UI.showPrize);
	EC.on(EVT.prizeSuccess, UI.prizeSuccess);
	EC.on(EVT.gameover, UI.gameover);
	EC.on(EVT.noMoney, UI.noMoney);
};



S.handleRoundResult = function(data){
	try{
		data = eval('(' + data + ')');
	} catch(err){
		data = {rate:50};
	}

	//0. 处理没花的情况.
	//1. 如果错了, 结束本局, 显示错过奖品和重新开始界面.
	//2. 如果对了且有奖品, 展示奖品, 询问是否继续.
	//  2.1 如果选择结束,领奖,展示领奖动画, 显示重新开始界面.
	//  2.2 如果选择继续,则继续.
	//3. 如果对了无奖品, 则继续.
	//TODO: 美化, 奖品逻辑
	if(data.error == 'NoMoney'){
		EC.fire(EVT.noMoney);
		
		return;
	}
	
	if(! data.win){ //失败
		EC.fire(EVT.gameover);
		return;
	} else {
		if(data.prize && data.prize.length){
			EC.fire(EVT.prizeShow, {prize: data.prize});
			return;
		}
		EC.fire(EVT.roundSuccess, {round:S.curRound});
		//S.showRoundResult(S.curRound, 1);
		S.nextRound();
	}

};
S.winPrize = function(prizeId){
	$.getJSON(C.winUrl, {prizeId:prizeId}, function(data){
		if(data.success){
			EC.fire(EVT.prizeSuccess, {prizeId: prizeId});
		}
	});
	//TODO 
	//1. 发送接受奖品请求
	//2. 领奖成功后提示是否重新开始
};
//预加载图片,以及数据
S.preload = function (loadNum){
	loadNum = loadNum || C.preloadCount; //默认提前加载4组
	var cache = S.preload._cache = S.preload._cache || {};

	if(S.curRound + loadNum >= S.data.length){
		$.getJSON(C.dataUrl, function(data){
			S.data = S.data.concat(data);
			//itemJson= itemJson.concat(data);
			S.preload();
		});
		return;
	}
	for(var i=0; i<loadNum; ++i){
		var idx = S.curRound + 1 + i;
		if(idx < S.data.length){
			var group = S.data[idx];
			for(var k=0; k < group.length; ++k){
				var o = group[k];
				if(! cache[o.id]){
					var img = new Image();
					img.src = o.pic_show_url;
					cache[o.id] = img;
					//log('preload:'+ o.id + " url:" +o.pic_show_url);	
				}
			}
		}
	}
};


S.startRound = function(n){
	EC.fire(EVT.roundStart, {round:n});
	//绘出图片
	//UI.drawRoundPics(n);
	//绘出其他元素
	//S.drawRoundEls(n);
	//预加载
	S.preload();
};

S.nextRound = function(){
	S.startRound(++S.curRound);
};


function initialize(){
	UI.initialize();
	S.startRound(1);
};
$(initialize);
